﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace llibreria_alsas
{
    class ConversorAutors : BDConnexio
    {
        public static void afegirAutors(Autors autor)
        {
            int idResultat = 0;
            SqlConnection con = obtenirConnexio();

            con.Open();

            SqlCommand selectId = new SqlCommand("Select max(id) from autors",con);
            Object val = selectId.ExecuteScalar();
            if (val != DBNull.Value)
            {
                idResultat = Convert.ToInt32(selectId.ExecuteScalar().ToString());
                idResultat++;
            }
            else
                idResultat = 1;
           
            
            SqlCommand insert = new SqlCommand("INSERT INTO Autors VALUES("+idResultat+",'"+autor.Nom+"','"+autor.Cognom+"')", con);
            insert.ExecuteNonQuery();

            con.Close();
        }

        public static DataTable seleccionarAutors()
        {
            SqlConnection con = obtenirConnexio();
            DataTable autors = new DataTable();
            SqlDataAdapter Dadapter;

            con.Open();

            Dadapter = new SqlDataAdapter("Select id, nom, cognom from autors", con);
            Dadapter.Fill(autors);

            con.Close();

            return autors;
        }

        public static void eliminarAutors(int id)
        {
            SqlConnection con = obtenirConnexio();
            con.Open();
            SqlCommand deleteId = new SqlCommand("Delete from Autors where id = " + id, con);
            deleteId.ExecuteNonQuery();
        }
    }
}
